package znet

import (
	"fmt"
	"github.com/pkg/errors"
	"my-zinx/ziface"
	"sync"
)

// ConnManager 连接管理
type ConnManager struct {
	connections map[uint64]ziface.IConnection // key: connID value: Conn
	connLock    sync.RWMutex                  // 读写锁
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint64]ziface.IConnection),
	}
}

func (c *ConnManager) Add(conn ziface.IConnection) {
	// 添加连接 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()

	c.connections[conn.GetConnID()] = conn

	fmt.Println("[Manager] connection add to ConnManager successfully: conn num = ", c.Len())
}

func (c *ConnManager) Remove(conn ziface.IConnection) {
	// 删除链接 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()

	delete(c.connections, conn.GetConnID())

	fmt.Println("[Manager] connection remove to ConnManager successfully: conn num = ", c.Len())
}

func (c *ConnManager) Get(connID uint64) (ziface.IConnection, error) {
	// 获取连接 加读锁
	c.connLock.RLock()
	defer c.connLock.RUnlock()

	conn, ok := c.connections[connID]
	if !ok {
		return nil, errors.Errorf("connID %d not exist", connID)
	}

	return conn, nil
}

func (c *ConnManager) Len() int {
	return len(c.connections)
}

func (c *ConnManager) ClearConn() {
	// 删除链接 加写锁
	c.connLock.Lock()
	defer c.connLock.Unlock()

	for connID, conn := range c.connections {
		conn.Stop()

		delete(c.connections, connID)
	}
	fmt.Println("[Manager] connection clear successfully: conn num = ", c.Len())
}
